// API 应用程序接口 Application Interface

// 前端和后端数据交换格式是 JSON 
const todos=[
    // todo
    {
        id:1,
        text:'todo1',
        finished:true
    },
    {
        id:2,
        text:'todo2',
        finished:false
    },
    {
        id:3,
        text:'todo3',
        finished:true
    },
    {
        id:4,
        text:'todo4',
        finished:false
    },
    {
        id:5,
        text:'todo5',
        finished:false
    }
]
// delay 函数
const delay=time=>new Promise(resolve=>setTimeout(resolve,time));
const withDelay=fn=>async(...args)=>{
    await delay(1000);
    return fn(...args);
}
// withDelay(function(){})(1,2,3)

export const fetchTodos=withDelay(params=>{
    // console.log(params);
    const {query,tab}=params;
    // console.log(query,tab);
    let result=todos;
    if(tab){
        switch(tab){
            case "finished":
                result=result.filter(todo=>todo.finished===true);
                break;
            case "unfinished":
                result=result.filter(todo=>todo.finished===false);
                break;
            default:
                break;
        }
    }
    if(query){
        result = result.filter(todo=>todo.text.includes(query));
    }
    // Promise 是异步同步化的一种方案 resolve 静态方法
    // Promise.resolve 返回一个fullfield 的Promise 的实例
    // 一般用于 返回结果的promise的实例化
    return Promise.resolve({
        tab,result
    })
})